<template>
	<view class="delivery-page">
		<!-- 订单信息骨架屏 -->
		<uv-skeletons :loading="loading" :animate="true" :skeleton="[
			{
				type: 'flex',
				style: 'background-color: #fff;padding: 30rpx;border-radius: 16rpx;',
				children: [
					{
						type: 'custom',
						style: 'width: 160rpx;height: 160rpx;border-radius: 8rpx;margin-right: 20rpx;'
					},
					{
						type: 'line',
						num: 3,
						style: [
							'width: 400rpx;height: 32rpx;',
							'width: 300rpx;height: 28rpx;margin-top: 20rpx;',
							'width: 200rpx;height: 28rpx;margin-top: 20rpx;'
						]
					}
				]
			},
			{
				type: 'line',
				style: 'margin-top: 30rpx;height: 40rpx;background-color: #fff;padding: 30rpx;border-radius: 16rpx;'
			}
		]">
			<!-- 订单信息卡片 -->
			<order-card :order="orderInfo" v-if="orderInfo"></order-card>

			<!-- 收货地址卡片 -->
			<view class="address-card" v-if="addressInfo">
				<view class="card-header">
					<text class="title">收货地址</text>
					<text class="copy-btn" @tap="copyAddress">复制地址</text>
				</view>
				<view class="address-content">
					<view class="user-info">
						<text class="name">{{ addressInfo.receiverName }}</text>
						<text class="phone">{{ addressInfo.receiverPhone }}</text>
					</view>
					<view class="address-detail">
						<text class="detail-text">{{ fullAddress }}</text>
					</view>
				</view>
			</view>
		</uv-skeletons>

		<!-- 物流信息表单 -->
		<view class="logistics-form">
			<view class="form-title">物流信息</view>

			<!-- 物流公司选择 -->
			<view class="form-item">
				<text class="label">物流公司(输入单号后点击识别自动填写)</text>
				<view class="input-wrapper" @tap="showCompanyPicker">
					<text :class="['placeholder', selectedCompany ? 'selected' : '']">
						{{ selectedCompany ? selectedCompany.name : '请选择物流公司' }}
					</text>
					<text class="iconfont icon-arrow-right"></text>
				</view>
			</view>

			<!-- 物流单号 -->
			<view class="form-item">
				<text class="label">物流单号</text>
				<view class="input-wrapper">
					<input type="text" v-model="trackingNo" placeholder="请输入物流单号" placeholder-class="placeholder"
						@input="onTrackingNoInput" />
					<text class="identify-btn" @tap="identifyExpressCompany" v-if="trackingNo">识别</text>
				</view>
			</view>
		</view>

		<!-- 提交按钮 -->
		<view class="submit-btn" @tap="submitDelivery">确认发货</view>

		<!-- 物流公司选择弹窗 -->
		<uv-popup ref="companyPopup" mode="bottom" :round="10">
			<view class="company-popup">
				<view class="popup-header">
					<text class="title">选择物流公司</text>
					<text class="close" @tap="hideCompanyPicker">×</text>
				</view>

				<!-- 搜索框 -->
				<view class="search-box">
					<text class="iconfont icon-search"></text>
					<input type="text" v-model="searchKeyword" placeholder="搜索物流公司" @input="searchCompanies" />
				</view>

				<!-- 物流公司列表 -->
				<scroll-view scroll-y class="company-list">
					<view class="company-item" v-for="company in companyList" :key="company.code"
						@tap="selectCompany(company)">
						<text class="company-name">{{ company.name }}</text>
						<text class="iconfont icon-check"
							v-if="selectedCompany && selectedCompany.code === company.code"></text>
					</view>
				</scroll-view>
			</view>
		</uv-popup>
	</view>
</template>

<script>
import OrderCard from '@/components/OrderCard/OrderCard.vue'

export default {
	components: {
		OrderCard
	},
	data() {
		return {
			loading: true,
			orderId: 0,
			orderInfo: null,
			addressInfo: null,
			selectedCompany: null,
			trackingNo: '',
			searchKeyword: '',
			companyList: [],
			timer: null,
			identifyTimer: null,
			possibleCompanies: [],
			lastIdentifiedNo: ''
		};
	},

	computed: {
		// 完整地址
		fullAddress() {
			if (!this.addressInfo) return '';
			const {
				province = '',
				city = '',
				district = '',
				street = '',
				detailAddress = '',
				addressDetail = ''
			} = this.addressInfo;

			// 基础地址
			const baseAddress = `${province}${city}${district}${street || ''}${detailAddress}`;

			// 如果有补充说明，添加到地址后面
			return addressDetail ? `${baseAddress} (${addressDetail})` : baseAddress;
		},

		// 用于复制的完整地址文本
		copyAddressText() {
			if (!this.addressInfo) return '';
			return `收货人：${this.addressInfo.receiverName}\n电话：${this.addressInfo.receiverPhone}\n地址：${this.fullAddress}`;
		}
	},

	onLoad(options) {
		this.orderId = options.orderId;
		this.loadOrderInfo();
		this.loadLogisticsCompanies();
	},

	methods: {
		// 加载订单信息
		async loadOrderInfo() {
			this.loading = true;
			try {
				const res = await this.$http.get(`/merchant/order/detail?orderId=${this.orderId}`);
				if (res) {
					this.orderInfo = res;
					// 加载地址信息
					if (res.addressId) {
						await this.loadAddressInfo(res.addressId);
					}
				}
			} catch (e) {
				uni.showToast({
					title: e.msg || '订单信息加载失败',
					icon: 'none'
				});
			} finally {
				this.loading = false;
			}
		},

		// 加载地址信息
		async loadAddressInfo(addressId) {
			try {
				const res = await this.$http.get(`/address/${addressId}`);
				if (res) {
					this.addressInfo = res;
				}
			} catch (e) {
				uni.showToast({
					title: e.msg || '地址信息加载失败',
					icon: 'none'
				});
			}
		},

		// 复制地址信息
		copyAddress() {
			uni.setClipboardData({
				data: this.copyAddressText,
				success: () => {
					uni.showToast({
						title: '地址已复制',
						icon: 'success'
					});
				}
			});
		},

		// 监听物流单号输入
		onTrackingNoInput() {
			// 清空已选择的物流公司
			this.selectedCompany = null;
			this.possibleCompanies = [];
			// 清空上次识别的单号，允许重新识别
			this.lastIdentifiedNo = '';
		},

		// 识别快递公司
		async identifyExpressCompany() {
			if (!this.trackingNo) {
				uni.showToast({
					title: '请输入物流单号',
					icon: 'none'
				});
				return;
			}

			// 如果是相同的单号，不重复识别
			if (this.lastIdentifiedNo === this.trackingNo) {
				uni.showToast({
					title: '请修改单号后再次识别',
					icon: 'none'
				});
				return;
			}

			try {
				const res = await this.$http.get('/logistics/identify?trackingNumber=' + this.trackingNo);

				if (res && res.status === '0' && res.list && res.list.length > 0) {
					// 记录已识别的单号
					this.lastIdentifiedNo = this.trackingNo;

					// 更新可能的快递公司列表
					this.possibleCompanies = res.list.map(item => ({
						code: item.type,
						name: item.name
					}));

					// 更新物流公司列表
					this.companyList = this.possibleCompanies;

					// 如果只有一个匹配结果，直接选中
					if (this.possibleCompanies.length === 1) {
						this.selectCompany(this.possibleCompanies[0]);
					} else {
						// 否则打开选择弹窗
						this.showCompanyPicker();
					}
				} else {
					// 识别失败时清空物流单号
					this.trackingNo = '';
					this.possibleCompanies = [];
					uni.showToast({
						title: res.msg || '无法识别快递公司',
						icon: 'none'
					});
				}
			} catch (e) {
				// 识别失败时清空物流单号
				this.trackingNo = '';
				this.possibleCompanies = [];
				uni.showToast({
					title: e.msg || '识别失败',
					icon: 'none'
				});
			}
		},

		// 加载物流公司列表
		async loadLogisticsCompanies() {
			try {
				const res = await this.$http.get('/logistics/companies');
				if (res) {
					this.companyList = res.list || [];
					// 如果有可能的快递公司，优先显示
					if (this.possibleCompanies.length > 0) {
						this.companyList = this.possibleCompanies;
					}
				}
			} catch (e) {
				uni.showToast({
					title: e.msg || '物流公司加载失败',
					icon: 'none'
				});
			}
		},

		// 搜索物流公司
		async searchCompanies() {
			if (this.timer) {
				clearTimeout(this.timer);
			}

			this.timer = setTimeout(async () => {
				if (!this.searchKeyword) {
					await this.loadLogisticsCompanies();
					return;
				}

				try {
					const res = await this.$http.get('/logistics/search?keyword=' + this.searchKeyword);
					if (res) {
						this.companyList = res || [];
					}
				} catch (e) {
					uni.showToast({
						title: e.msg || '搜索失败',
						icon: 'none'
					});
				}
			}, 300);
		},

		// 显示物流公司选择器
		showCompanyPicker() {
			this.$refs.companyPopup.open();
		},

		// 隐藏物流公司选择器
		hideCompanyPicker() {
			this.$refs.companyPopup.close();
		},

		// 选择物流公司
		selectCompany(company) {
			this.selectedCompany = company;
			this.hideCompanyPicker();
		},

		// 提交发货
		async submitDelivery() {
			if (!this.selectedCompany) {
				uni.showToast({
					title: '请选择物流公司',
					icon: 'none'
				});
				return;
			}

			if (!this.trackingNo) {
				uni.showToast({
					title: '请输入物流单号',
					icon: 'none'
				});
				return;
			}

			if (!this.orderInfo || !this.orderInfo.addressId) {
				uni.showToast({
					title: '订单信息不完整',
					icon: 'none'
				});
				return;
			}

			try {
				const res = await this.$http.post('/merchant/ship/order', {
					orderId: this.orderId,
					merchantId: this.orderInfo.merchantId,
					addressId: this.orderInfo.addressId,
					trackingNumber: this.trackingNo,
					logisticsCode: this.selectedCompany.code,
					logisticsCompany: this.selectedCompany.name,
					phone: this.addressInfo.receiverPhone
				});

				if (res) {
					uni.showToast({
						title: '发货成功'
					});
				} else {
					uni.showToast({
						title: res.msg || '发货失败',
							icon: 'none'
					});
				}

				setTimeout(() => {
					uni.navigateBack();
				}, 1500);
			} catch (e) {
				uni.showToast({
					title: e.msg || '发货失败',
					icon: 'none'
				});
			}
		}
	}
}
</script>

<style lang="scss" scoped>
@import './goods_delivery_page.scss';
</style>
